package org.zjt.java.demo.config.security;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

public class AuthenticationTokenFilter extends UsernamePasswordAuthenticationFilter {

    @Value("${merchant.token.header}")
    private String tokenHeader;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authToken = httpRequest.getHeader(this.tokenHeader);
        if (StringUtils.isEmpty(authToken)) {
            Cookie[] cookies = httpRequest.getCookies();//这样便可以获取一个cookie数组
            if (cookies != null) {
                Optional<Cookie> any = Arrays.stream(cookies).filter(i -> i != null).filter(i -> i.getName().equals(this.tokenHeader)).findAny();
                if (any.isPresent())
                    authToken = any.get().getValue();
            }
        }
        String userDetailsJson = this.tokenUtils.getUsernameFromToken(authToken);
        SecurityUser userDetails = StringUtils.isEmpty(userDetailsJson) ? null : JSONObject.parseObject(userDetailsJson, SecurityUser.class);
        if (userDetails == null)
            SecurityContextHolder.getContext().setAuthentication(null);
        // 用页面传过来的token，以及token中携带的用户名，查询该token是否ok，从而知道是否认证成功。
        if (userDetails != null && !StringUtils.isEmpty(userDetails.getUsername()) && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails tmp = this.userDetailsService.loadUserByUsername(userDetails.getUsername());
            if (this.tokenUtils.validateToken(authToken, tmp)) {//token有效的
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(tmp, null, tmp.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }


}
